import torch
import torch.nn as nn
import torch.optim as optim
import sys
import os

# 添加模块路径
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from moudle import (
    create_data_loaders, 
    Trainer, 
    setup_device, 
    load_label_mapping,
    TensorBoardLogger,
    YAMLConfig
)


# AlexNet模型定义
class AlexNet(nn.Module):
    def __init__(self, num_classes=100):
        super(AlexNet, self).__init__()
        self.features = nn.Sequential(
            nn.Conv2d(3, 96, kernel_size=11, stride=4, padding=1), 
            nn.BatchNorm2d(96),  # 添加BN
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(96, 256, kernel_size=5, padding=2),
            nn.BatchNorm2d(256),  # 添加BN
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),

            nn.Conv2d(256, 384, kernel_size=3, padding=1),
            nn.BatchNorm2d(384),  # 添加BN
            nn.ReLU(inplace=True),

            nn.Conv2d(384, 384, kernel_size=3, padding=1),
            nn.BatchNorm2d(384),  # 添加BN
            nn.ReLU(inplace=True),

            nn.Conv2d(384, 256, kernel_size=3, padding=1),
            nn.BatchNorm2d(256),  # 添加BN
            nn.ReLU(inplace=True),
            nn.MaxPool2d(kernel_size=3, stride=2),
        )

        # 自动计算展平后的尺寸
        with torch.no_grad():
            dummy_input = torch.zeros(1, 3, 224, 224)
            self.flattened_size = self.features(dummy_input).flatten(1).shape[1]

        self.classifier = nn.Sequential(
            nn.Dropout(p=0.5),
            nn.Linear(self.flattened_size, 4096),  # 使用自动计算的尺寸
            nn.ReLU(inplace=True),
            nn.Dropout(p=0.5),
            nn.Linear(4096, 4096),
            nn.ReLU(inplace=True),
            nn.Linear(4096, num_classes),
        )

    def forward(self, x):
        x = self.features(x)
        x = x.flatten(1)
        x = self.classifier(x)
        return x


def main():
    # 从YAML文件加载配置
    config_file = os.path.join(os.path.dirname(__file__), 'config.yaml')
    config = YAMLConfig(config_file)
    
    print("=== AlexNet 训练 (使用模块化框架) ===")
    
    # 1. 设置设备
    device = setup_device()
    
    # 2. 创建数据加载器
    print("\n加载数据集...")
    train_loader, val_loader, test_loader, train_dataset = create_data_loaders(
        data_dir=config.get('data_dir'),
        batch_size=config.get('batch_size'),
        num_workers=config.get('num_workers'),
        pin_memory=config.get('pin_memory'),
        img_size=config.get('img_size'),
        mean=config.get('normalize_mean'),
        std=config.get('normalize_std')
    )
    
    # 3. 加载标签映射
    label_mapping = load_label_mapping(config.get('label_file'))
    
    # 4. 创建模型
    print("\n创建模型...")
    model = AlexNet(num_classes=config.get('num_classes'))
    
    # 5. 创建损失函数和优化器
    criterion = nn.CrossEntropyLoss()
    optimizer = optim.SGD(
        model.parameters(), 
        lr=config.get('lr'), 
        momentum=config.get('momentum'), 
        weight_decay=config.get('weight_decay')
    )
    
    # 6. 创建学习率调度器
    if config.get('scheduler_type') == 'StepLR':
        scheduler = optim.lr_scheduler.StepLR(
            optimizer, 
            step_size=config.get('step_size'), 
            gamma=config.get('gamma')
        )
    else:
        scheduler = None
    
    # 7. 创建TensorBoard记录器
    tensorboard_logger = TensorBoardLogger(
        log_dir=config.get('log_dir'),
        model_name='alexnet',
        comment='yaml_config'
    )
    
    # 8. 创建训练器
    trainer = Trainer(
        model=model,
        device=device,
        criterion=criterion,
        optimizer=optimizer,
        scheduler=scheduler,
        tensorboard_logger=tensorboard_logger,
        model_save_path=config.get('model_save_path'),
        print_freq=config.get('print_freq')
    )
    
    # 9. 开始训练
    training_history = trainer.train(
        train_loader=train_loader,
        val_loader=val_loader,
        num_epochs=config.get('num_epochs'),
        save_best=config.get('save_best')
    )
    
    # 10. 测试模型
    print('\n加载最佳模型进行测试...')
    # 加载最佳模型
    best_model_path = config.get('model_save_path').replace('.pth', '_best.pth')
    if os.path.exists(best_model_path):
        checkpoint = torch.load(best_model_path, map_location=device)
        model.load_state_dict(checkpoint['model_state_dict'])
        print(f"加载最佳模型成功，验证准确率: {checkpoint['val_acc']:.2f}%")
    
    # 重新创建测试用的训练器
    test_trainer = Trainer(model=model, device=device)
    test_accuracy = test_trainer.test(
        test_loader=test_loader,
        train_dataset=train_dataset,
        label_mapping=label_mapping,
        num_classes=config.get('num_classes')
    )
    
    # 10. 记录最终结果
    tensorboard_logger.log_test_results(test_accuracy)
    tensorboard_logger.log_final_summary(
        training_time=training_history['training_time'],
        best_val_acc=training_history['best_val_acc'],
        test_acc=test_accuracy,
        model_path=config.get('model_save_path')
    )
    
    # 11. 打印最终结果
    print(f'\n=== 训练总结 ===')
    print(f'训练时间: {training_history["training_time"]:.2f} 秒')
    print(f'最佳验证准确率: {training_history["best_val_acc"]:.2f}%')
    print(f'最终测试准确率: {test_accuracy:.2f}%')
    print(f'模型已保存至: {config.get("model_save_path")}')
    
    # 12. 打印配置信息
    print(f'\n=== 使用的配置 ===')
    config.print_config()
    
    # 13. 关闭TensorBoard并打印命令
    tensorboard_logger.print_tensorboard_command()
    tensorboard_logger.close()


if __name__ == '__main__':
    main() 